package upload

import (
	"bytes"
	"context"
	"fmt"
	"gitee.com/filters/utils/character"
	"github.com/aliyun/aliyun-oss-go-sdk/oss"
	"io"
	"path/filepath"
)

type Aliyuner struct {
	cfg    UploadCfg
	bucket *oss.Bucket
	err    error
}

// NewAlier ...
func NewAlier(url, key, secret, bucketName, path string) *Aliyuner {
	ali := &Aliyuner{
		cfg: UploadCfg{
			ossUrl:       url,
			accessKey:    key,
			accessSecret: secret,
			bucketName:   bucketName,
			path:         path,
		},
	}

	client, err := oss.New(url, key, secret)
	if err != nil {
		ali.err = err
		return ali
	}
	// 指定bucket
	bucket, err := client.Bucket(bucketName) // 根据自己的填写
	if err != nil {
		ali.err = err
		return ali
	}
	ali.bucket = bucket
	return ali
}

// Upload ...
func (a *Aliyuner) Upload(ctx context.Context, fileCfg *FileCfg) (string, error) {
	name := character.GetUid() + filepath.Ext(fileCfg.Name)
	if a.err != nil {
		return name, a.err
	}
	fmt.Println(filepath.Ext(fileCfg.Name))
	path := a.cfg.path + name
	err := a.bucket.PutObject(path, bytes.NewReader(fileCfg.File))
	if err != nil {
		return name, err
	}
	return name, nil
}

// Download ...
func (a *Aliyuner) Download(ctx context.Context, fileCfg *FileCfg) ([]byte, error) {
	var data []byte
	if a.err != nil {
		return data, a.err
	}
	path := a.cfg.path + fileCfg.Name
	// 下载文件到流。
	body, err := a.bucket.GetObject(path)
	if err != nil {
		return data, err
	}
	// 数据读取完成后，获取的流必须关闭，否则会造成连接泄漏，导致请求无连接可用，程序无法正常工作。
	defer body.Close()
	data, err = io.ReadAll(body)
	if err != nil {
		return data, err
	}
	return data, nil
}
